package com.yfuxdeer.youchat.service;

import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;

import androidx.annotation.Nullable;

import com.yfuxdeer.youchat.dao.UserDao;
import com.yfuxdeer.youchat.dao.impl.UserDaoImpl;
import com.yfuxdeer.youchat.pojo.User;

import java.io.Serializable;
import java.util.List;
import java.util.Random;

public class UserService extends Service {

    private final String TAG = UserService.class.getSimpleName();
    private UserDao userDao = new UserDaoImpl();
    private Bundle bundle;
    private Bundle data;


    public enum METHOD {
        LOGIN,
        UPDATE,
        FIND_USER,
        REGISTER,
        SERACH
    }

    public enum RESULT {
        SUCCESS, ERROR, NETWORK_EXCEPTION, ALREDY_REGISTER
    }

    /**
     * 注册用户，接受LoginActivity的intent获取参数，并将结果广播回去
     */
    public void login() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String username = bundle.getString("username");
                    String password = bundle.getString("password");
                    User loginUser = userDao.queryByUsernameAndPassword(username, password);
                    if (loginUser != null) {
                        data.putSerializable("result", RESULT.SUCCESS);
                        data.putSerializable("loginUser", loginUser);
                    } else {
                        data.putSerializable("result", RESULT.ERROR);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    data.putSerializable("result", RESULT.NETWORK_EXCEPTION);
                }
                Intent broadcast = new Intent("com.yfuxdeer.youchat.loginReceiver");
                broadcast.putExtras(data);
                sendBroadcast(broadcast);
            }
        }).start();
    }

    /**
     * 修改用户，接受UserInfoActivity的intent参数，并将结果广播回去
     */
    public void updateUser() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                User user = (User) bundle.getSerializable("user");
                try {
                    userDao.update(user);
                    data.putSerializable("user", user);
                    data.putSerializable("result", RESULT.SUCCESS);
                } catch (Exception e) {
                    data.putSerializable("result", RESULT.NETWORK_EXCEPTION);
                }
                Intent broadcast = new Intent("com.yfuxdeer.youchat.updateUserReceiver");
                broadcast.putExtras(data);
                sendBroadcast(broadcast);
            }
        }).start();
    }

    //查找用户
    public void findUserById() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                String user_id = bundle.getString("user_id");
                try {
                    User user = userDao.findUserById(user_id);
                    data.putSerializable("user", user);
                    data.putSerializable("result", RESULT.SUCCESS);
                } catch (Exception e) {
                    data.putSerializable("result", RESULT.NETWORK_EXCEPTION);
                }
                Intent broadcast = new Intent("com.yfuxdeer.youchat.findUserReceiver");
                broadcast.putExtras(data);
                sendBroadcast(broadcast);
            }
        }).start();
    }

    //注册
    public void registerUser() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String username = generateUsername();
                    User user = (User) bundle.getSerializable("user");
                    user.setUsername(username);
                    User u = null;
                    if (user.getEmail().contains("@")) {
                        //使用邮箱注册的
                        u = userDao.findUserByPhoneOrEmail(user.getEmail());
                    } else {
                        u = userDao.findUserByPhoneOrEmail(user.getPhone());
                    }
                    if (u != null) {
                        //修改密码
                        u.setPassword(user.getPassword());
                        userDao.updatePassword(u.getUsername(), u.getPassword());
                        data.putString("password", u.getPassword());
                        data.putSerializable("result", RESULT.ALREDY_REGISTER);
                    } else {
                        //注册账号
                        userDao.insert(user);
                        data.putString("username", user.getUsername());
                        data.putSerializable("result", RESULT.SUCCESS);
                    }
                } catch (Exception e) {
                    data.putSerializable("result", RESULT.NETWORK_EXCEPTION);
                }
                Intent broadcast = new Intent("com.yfuxdeer.youchat.registerReceiver");
                broadcast.putExtras(data);
                sendBroadcast(broadcast);
            }
        }).start();
    }

    //搜索除自己的用户
    public void searchUserList() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String username = bundle.getString("username");
                    String info = bundle.getString("info");
                    List<User> users = userDao.searchUserByInfo(username, info);
                    data.putSerializable("users", (Serializable) users);
                    data.putSerializable("result", RESULT.SUCCESS);
                } catch (Exception e) {
                    data.putSerializable("result", RESULT.NETWORK_EXCEPTION);
                }
                Intent broadcast = new Intent("com.yfuxdeer.youchat.searchReceiver");
                broadcast.putExtras(data);
                sendBroadcast(broadcast);
            }
        }).start();
    }

    private String generateUsername() throws Exception {
        Random random = new Random();
        int c = random.nextInt(10) + 1;
        String[] nums = new String[]{"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"};
        StringBuffer buffer;
        do {
            buffer = new StringBuffer();
            for (int i = 0; i < c; i++) {
                buffer.append(nums[random.nextInt(10)]);
            }
        } while (!check(buffer.toString()));
        return buffer.toString();
    }


    private boolean check(String username) throws Exception {
        return userDao.findUserById(username) == null;
    }


    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        bundle = intent.getExtras();
        data = new Bundle();
        METHOD method = (METHOD) bundle.getSerializable("method");
        switch (method) {
            case LOGIN:
                login();
                break;
            case UPDATE:
                updateUser();
                break;
            case FIND_USER:
                findUserById();
                break;
            case REGISTER:
                registerUser();
                break;
            case SERACH:
                searchUserList();
        }
        stopSelf();
        return super.onStartCommand(intent, flags, startId);
    }
}
